package com.loopstack.gprint.io;


import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;


import com.loopstack.gprint.utils.CallbackListener;
import com.loopstack.gprint.utils.Command;
import com.loopstack.gprint.utils.GpUtils;
import com.loopstack.gprint.utils.HexUtils;
import com.loopstack.gprint.utils.LogUtils;
import com.loopstack.gprint.io.PortManager;
import  com.loopstack.gprint.io.PrinterDevices;
import com.loopstack.gprint.utils.SDKUtils;
import com.loopstack.gprint.utils.UIThreadManager;
import com.loopstack.gprint.utils.PDFUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.Vector;

public class BluetoothPort extends PortManager {
    private static final String TAG = BluetoothPort.class.getSimpleName();
    private static final UUID SERIAL_PORT_SERVICE_CLASS_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private BluetoothAdapter mAdapter = null;
    private BluetoothDevice device;
    private BluetoothSocket mSocket;
    private int len = -1;
    private String macAddress;
    private CallbackListener callbackListener;
    private List<CallbackListener> callbackListenerList = new ArrayList();
    private Command command = null;
    private byte[] buffer = new byte[128];
    private boolean isConn = false;
    private boolean isSafety = false;
    private IoReader reader = null;
    private final Object lock = new Object();
    private PrinterDevices mPrinterDevices = null;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();


    public boolean getConnectStatus() {
        return this.isConn;
    }

    public BluetoothPort(PrinterDevices printerDevices) {
        if (printerDevices != null) {
            this.mPrinterDevices = printerDevices;
            this.macAddress = printerDevices.getMacAddress();
            this.callbackListener = printerDevices.getCallbackListener();
            this.command = printerDevices.getCommand();
            this.isSafety = printerDevices.isSafety();
        }

    }

    public void addCallBackListener(CallbackListener listener) {
        this.callbackListenerList.add(listener);
    }

    public void removeCallBackListener(CallbackListener listener) {
        this.callbackListenerList.remove(listener);
    }

    @Override
    public boolean openPort() {
        LogUtils.e(TAG, "try to open connect printer");
        this.mAdapter = BluetoothAdapter.getDefaultAdapter();
        if (this.mAdapter == null) {
            throw new RuntimeException("The device does not support Bluetooth！");
        } else {
            if (this.mAdapter.isDiscovering()) {
                this.mAdapter.cancelDiscovery();
            }

            if (!this.mAdapter.isEnabled()) {
                LogUtils.e(TAG, "Bluetooth is not turned on...");
                return false;
            } else {
                try {
                    if (this.callbackListener != null) {
                        UIThreadManager.onUIThread(new Runnable() {
                            public void run() {
                                BluetoothPort.this.callbackListener.onConnecting();
                            }
                        });
                    }

                    if (BluetoothAdapter.checkBluetoothAddress(this.macAddress)) {
                        this.device = this.mAdapter.getRemoteDevice(this.macAddress);
                        this.mPrinterDevices.setBlueName(this.device.getName());
                        if (this.isSafety) {
                            this.mSocket = this.device.createRfcommSocketToServiceRecord(SERIAL_PORT_SERVICE_CLASS_UUID);
                        } else {
                            this.mSocket = this.device.createInsecureRfcommSocketToServiceRecord(SERIAL_PORT_SERVICE_CLASS_UUID);
                        }

                        this.mSocket.connect();
                        this.inputStream = this.mSocket.getInputStream();
                        this.outputStream = this.mSocket.getOutputStream();
                        this.isConn = true;
                        if (this.callbackListener != null) {
                            if (this.command == null) {
                                UIThreadManager.onUIThread(new Runnable() {
                                    public void run() {
                                        BluetoothPort.this.callbackListener.onCheckCommand();
                                    }
                                });
                                this.checkPrinterCommand();
                            } else {
                                this.setSuccessListen(this.command);
                            }
                        }

                        this.reader = new IoReader();
                        this.reader.start();
                        return true;
                    } else {
                        new RuntimeException("Bluetooth address is invalid");
                        this.setFailureListen();
                        return false;
                    }
                } catch (IOException var2) {
                    this.setFailureListen();
                    return false;
                }
            }
        }
    }

    private void checkPrinterCommand() throws IOException {
        int status = this.getPrinterStatus(Command.ESC);
        if (status == -1) {
            status = this.getPrinterStatus(Command.CPCL);
            if (status == -1) {
                status = this.getPrinterStatus(Command.TSC);
                if (status == -1) {
                    this.setFailureListen();
                } else {
                    this.setSuccessListen(Command.TSC);
                }
            } else {
                this.setSuccessListen(Command.CPCL);
            }
        } else {
            this.setSuccessListen(Command.ESC);
        }

    }

    private void setSuccessListen(Command command) {
        this.command = command;
        this.mPrinterDevices.setCommand(command);
        if (this.callbackListener != null) {
            UIThreadManager.onUIThread(new Runnable() {
                public void run() {
                    BluetoothPort.this.callbackListener.onSuccess(BluetoothPort.this.mPrinterDevices);
                }
            });
        }

    }

    private void setFailureListen() {
        if (this.callbackListener != null) {
            UIThreadManager.onUIThread(new Runnable() {
                public void run() {
                    BluetoothPort.this.callbackListener.onFailure();
                }
            });
        }

    }

    public boolean writeDataImmediately(byte[] data) throws IOException {
        if (this.mSocket != null && this.outputStream != null && data != null) {
            try {
                this.outputStream.write(data, 0, data.length);
                this.outputStream.flush();
                return true;
            } catch (IOException var3) {
                Log.e(TAG, "Exception occur while sending data immediately: ", var3);
                this.isConn = false;
                if (this.callbackListener != null) {
                    UIThreadManager.onUIThread(new Runnable() {
                        public void run() {
                            BluetoothPort.this.callbackListener.onDisconnect();
                        }
                    });
                }

                throw var3;
            }
        } else {
            return false;
        }
    }

    public PrinterDevices getPrinterDevices() {
        return this.mPrinterDevices;
    }

    public boolean writeDataImmediately(Vector<Byte> data) throws IOException {
        if (this.mSocket != null && this.outputStream != null && data != null) {
            boolean var2;
            try {
                Log.e(TAG, "send\r\n" + data.size() + "\t" + SDKUtils.bytesToHexString(SDKUtils.convertVectorByteToBytes(data)));
                this.outputStream.write(SDKUtils.convertVectorByteToBytes(data), 0, data.size());
                this.outputStream.flush();
                var2 = true;
            } catch (IOException var6) {
                Log.e(TAG, "Exception occur while sending data to printer: ", var6);
                this.isConn = false;
                if (this.callbackListener != null) {
                    UIThreadManager.onUIThread(new Runnable() {
                        public void run() {
                            BluetoothPort.this.callbackListener.onDisconnect();
                        }
                    });
                }

                throw var6;
            } finally {
                data.clear();
            }

            return var2;
        } else {
            return false;
        }
    }

    public int getPrinterStatus(Command command) throws IOException {
        if (command == null) {
            return -1;
        } else {
            synchronized(this.lock) {
                if (this.byteArrayOutputStream.size() > 0) {
                    this.byteArrayOutputStream.reset();
                }
            }

            byte[] recv;
            switch (command) {
                case ESC:
                    byte[] esc = new byte[]{16, 4, 2};
                    this.writeDataImmediately(esc);
                    break;
                case TSC:
                    byte[] tsc = new byte[]{27, 33, 63, 13, 10};
                    this.writeDataImmediately(tsc);
                    break;
                case CPCL:
                    recv = new byte[]{27, 104};
                    this.writeDataImmediately(recv);
            }

            long endTime = SystemClock.uptimeMillis() + 2000L;
            recv = null;
            int length = 0;
            if (this.reader == null) {
                do {
                    if (this.inputStream.available() > 0) {
                        if (recv == null) {
                            recv = new byte[this.inputStream.available()];
                        }

                        length = this.inputStream.read(recv);
                    }

                    if (length > 0) {
                        break;
                    }

                    try {
                        Thread.sleep(100L);
                    } catch (InterruptedException var10) {
                    }
                } while(endTime > SystemClock.uptimeMillis());
            } else {
                synchronized(this.lock) {
                    while(this.byteArrayOutputStream.size() == 0 && endTime > SystemClock.uptimeMillis()) {
                        try {
                            this.lock.wait(500L);
                        } catch (InterruptedException var9) {
                        }
                    }

                    if (this.byteArrayOutputStream != null && this.byteArrayOutputStream.size() > 0) {
                        length = this.byteArrayOutputStream.size();
                        recv = this.byteArrayOutputStream.toByteArray();
                    }
                }

                if (recv != null) {
                    LogUtils.e("model length" + length + "\thex:\t" + HexUtils.byte2HexStr(recv));
                }
            }

            if (length > 0) {
                switch (command) {
                    case ESC:
                        if (recv[0] == 18) {
                            return 0;
                        }

                        if ((recv[0] & 32) > 0) {
                            return -2;
                        }

                        if ((recv[0] & 4) > 0) {
                            return -3;
                        }

                        if ((recv[0] & 64) > 0) {
                            return -4;
                        }
                        break;
                    case TSC:
                        if (recv[0] == 0) {
                            return 0;
                        }

                        if ((recv[0] & 32) > 0) {
                            return 1;
                        }

                        if ((recv[0] & 4) > 0) {
                            return -2;
                        }

                        if ((recv[0] & 1) > 0) {
                            return -3;
                        }

                        if ((recv[0] & 128) > 0) {
                            return -4;
                        }

                        if ((recv[0] & 2) > 0) {
                            return -5;
                        }

                        if ((recv[0] & 3) > 0) {
                            return -6;
                        }

                        if ((recv[0] & 5) > 0) {
                            return -7;
                        }

                        if ((recv[0] & 8) > 0) {
                            return -8;
                        }

                        if ((recv[0] & 9) > 0) {
                            return -9;
                        }

                        if ((recv[0] & 10) > 0) {
                            return -10;
                        }

                        if ((recv[0] & 11) > 0) {
                            return -11;
                        }

                        if ((recv[0] & 12) > 0) {
                            return -12;
                        }

                        if ((recv[0] & 13) > 0) {
                            return -13;
                        }

                        if ((recv[0] & 16) > 0) {
                            return -14;
                        }
                        break;
                    case CPCL:
                        if (recv[0] == 0) {
                            return 0;
                        }

                        if ((recv[0] & 1) > 0) {
                            return 1;
                        }

                        if (recv[0] == 2) {
                            return -2;
                        }

                        if (recv[0] == 4) {
                            return -3;
                        }

                        if (recv[0] == 6) {
                            return -4;
                        }
                }

                return recv[0] & 255;
            } else {
                return -1;
            }
        }
    }

    public byte[] getKey() throws IOException {
        synchronized(this.lock) {
            if (this.byteArrayOutputStream.size() > 0) {
                this.byteArrayOutputStream.reset();
            }
        }

        String command = "READ_INFO ID\r\n";
        this.writeDataImmediately(command.getBytes("GB18030"));
        long endTime = SystemClock.uptimeMillis() + 3000L;
        byte[] recv = null;
        int len = 0;
        if (this.reader == null) {
            do {
                if (this.inputStream.available() > 0) {
                    recv = new byte[this.inputStream.available()];
                    len = this.inputStream.read(recv);
                }

                if (len > 0) {
                    break;
                }

                try {
                    Thread.sleep(100L);
                } catch (InterruptedException var10) {
                }
            } while(endTime > SystemClock.uptimeMillis());
        } else {
            synchronized(this.lock) {
                while(this.byteArrayOutputStream.size() == 0 && endTime > SystemClock.uptimeMillis()) {
                    try {
                        this.lock.wait(500L);
                    } catch (InterruptedException var9) {
                    }
                }

                if (this.byteArrayOutputStream != null && this.byteArrayOutputStream.size() > 0) {
                    return this.byteArrayOutputStream.toByteArray();
                }
            }
        }

        return null;
    }

    public int getPower() throws IOException {
        synchronized(this.lock) {
            if (this.byteArrayOutputStream != null && this.byteArrayOutputStream.size() > 0) {
                this.byteArrayOutputStream.reset();
            }
        }

        byte[] command = new byte[]{31, 27, 31, -88, 16, 17, 18, 19, 20, 21, 119};
        this.writeDataImmediately(command);
        long endTime = SystemClock.uptimeMillis() + 2000L;
        byte[] recv = null;
        if (this.reader == null) {
            do {
                if (this.inputStream.available() > 0) {
                    if (recv == null) {
                        recv = new byte[this.inputStream.available()];
                    }

                    this.inputStream.read(recv);
                }

                if (recv != null && recv.length > 0) {
                    break;
                }

                try {
                    Thread.sleep(100L);
                } catch (InterruptedException var9) {
                }
            } while(endTime > SystemClock.uptimeMillis());
        } else {
            synchronized(this.lock) {
                while(this.byteArrayOutputStream.size() == 0 && endTime > SystemClock.uptimeMillis()) {
                    try {
                        this.lock.wait(500L);
                    } catch (InterruptedException var8) {
                    }
                }

                if (this.byteArrayOutputStream != null && this.byteArrayOutputStream.size() > 0 && recv == null) {
                    recv = this.byteArrayOutputStream.toByteArray();
                }
            }
        }

        if (recv != null && recv.length > 0) {
            if (recv[0] == 49) {
                return 1;
            } else if (recv[0] == 50) {
                return 2;
            } else if (recv[0] == 51) {
                return 3;
            } else if (recv[0] == 52) {
                return 4;
            } else {
                return recv[0] == 53 ? 5 : recv[0] & 255;
            }
        } else {
            return -1;
        }
    }

    public String getPrinterModel(Command command) throws IOException {
        if (command == null) {
            return "";
        } else {
            synchronized(this.lock) {
                if (this.byteArrayOutputStream.size() > 0) {
                    this.byteArrayOutputStream.reset();
                }
            }

            byte[] recv;
            switch (command) {
                case ESC:
                    byte[] esc = new byte[]{29, 73, 67};
                    this.writeDataImmediately(esc);
                    break;
                case TSC:
                    byte[] tsc = new byte[]{126, 33, 84, 13, 10};
                    this.writeDataImmediately(tsc);
                    break;
                case CPCL:
                    recv = new byte[]{27, 118};
                    this.writeDataImmediately(recv);
            }

            long endTime = SystemClock.uptimeMillis() + 2000L;
            recv = null;
            if (this.reader != null) {
                synchronized(this.lock) {
                    while(endTime > SystemClock.uptimeMillis()) {
                        try {
                            this.lock.wait(500L);
                        } catch (InterruptedException var8) {
                        }
                    }
                }
            } else {
                do {
                    if (this.inputStream.available() > 0) {
                        if (recv == null) {
                            recv = new byte[this.inputStream.available()];
                        }

                        this.inputStream.read(recv);
                    }

                    try {
                        Thread.sleep(100L);
                    } catch (InterruptedException var9) {
                    }
                } while(endTime > SystemClock.uptimeMillis());
            }

            if (this.byteArrayOutputStream != null && this.byteArrayOutputStream.size() > 0) {
                LogUtils.e("model length" + this.byteArrayOutputStream.size());
                return this.byteArrayOutputStream.toString();
            } else {
                return null;
            }
        }
    }

    public void setCommand(Command command) {
        this.command = command;
    }

    public Command getCommand() {
        return this.command;
    }

    public static Bitmap cutBitmap(Bitmap bitmap, int y, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Log.e(String.valueOf(w), String.valueOf(h));
        return Bitmap.createBitmap(bitmap, 0, y, w, height, (Matrix)null, false);
    }

    @RequiresApi(
            api = 21
    )
    public boolean writePDFToEsc(File file, int width) throws Exception {
        Bitmap[] bitmaps = PDFUtils.PDFToBitmap(file, width);
        if (bitmaps == null) {
            return false;
        } else {
            for(int i = 0; i < bitmaps.length; ++i) {
                byte[] data = PDFUtils.drawEscPDF(bitmaps[i]);
                this.writeDataImmediately(data);
                if (i == bitmaps.length - 1) {
                    return true;
                }
            }

            byte[] command = new byte[]{10, 29, 86, 66, 0, 27, 64};
            this.writeDataImmediately(command);
            return false;
        }
    }

    @RequiresApi(
            api = 21
    )
    public boolean writePDFToTsc(File file, int printWidth, int gap, boolean cut, boolean dpi200, boolean compression, int cutHeight) throws Exception {
        if (file == null) {
            throw new Exception("File cannot be empty");
        } else if (TextUtils.isEmpty(String.valueOf(printWidth))) {
            throw new Exception("printWidth cannot be empty");
        } else if (TextUtils.isEmpty(String.valueOf(gap))) {
            throw new Exception("gap cannot be empty");
        } else if (TextUtils.isEmpty(String.valueOf(cutHeight))) {
            throw new Exception("cutHeight cannot be empty");
        } else {
            Bitmap[] bitmaps = PDFUtils.PDFToBitmap(file, printWidth);
            if (bitmaps == null) {
                return false;
            } else {
                int i;
                String cls;
                String print;
                if (gap > 0 | cutHeight == 0) {
                    for(i = 0; i < bitmaps.length; ++i) {
                        String size = "\r\nSIZE " + bitmaps[i].getWidth() / (dpi200 ? 8 : 12) + " mm," + bitmaps[i].getHeight() / (dpi200 ? 8 : 12) + " mm\r\n";
                        this.writeDataImmediately(size.getBytes("GB18030"));
                        String GAP = "GAP " + gap + " mm,0 mm\r\n";
                        if (cut && i == bitmaps.length - 1) {
                            this.writeDataImmediately("SET CUTTER 1\r\n".getBytes("GB18030"));
                        } else {
                            this.writeDataImmediately("SET CUTTER OFF\r\n".getBytes("GB18030"));
                        }

                        this.writeDataImmediately(GAP.getBytes("GB18030"));
                        cls = "CLS\r\n";
                        this.writeDataImmediately(cls.getBytes("GB18030"));
                        byte[] data;
                        if (compression) {
                            data = PDFUtils.drawTscPDFLib(bitmaps[i]);
                            this.writeDataImmediately(data);
                        } else {
                            data = PDFUtils.drawTscPDF(bitmaps[i]);
                            this.writeDataImmediately(data);
                        }

                        print = "\r\nPRINT 1\r\n";
                        this.writeDataImmediately(print.getBytes("GB18030"));
                        if (i == bitmaps.length - 1) {
                            return true;
                        }
                    }
                } else {
                    for(i = 0; i < bitmaps.length; ++i) {
                        List<Bitmap> mlist = ImageCrop(bitmaps[i], cutHeight);

                        for(int j = 0; j < mlist.size(); ++j) {
                            cls = "\r\nSIZE " + ((Bitmap)mlist.get(j)).getWidth() / (dpi200 ? 8 : 12) + " mm," + ((Bitmap)mlist.get(j)).getHeight() / (dpi200 ? 8 : 12) + " mm\r\n";
                            this.writeDataImmediately(cls.getBytes("GB18030"));
                            String GAP = "GAP 0 mm,0 mm\r\n";
                            if (cut && j == mlist.size() - 1 && i == bitmaps.length - 1) {
                                this.writeDataImmediately("SET CUTTER 1\r\n".getBytes("GB18030"));
                            } else {
                                this.writeDataImmediately("SET CUTTER OFF\r\n".getBytes("GB18030"));
                            }

                            this.writeDataImmediately(GAP.getBytes("GB18030"));
                            print = "CLS\r\n";
                            this.writeDataImmediately(print.getBytes("GB18030"));
                            byte[] data;
                            if (compression) {
                                data = PDFUtils.drawTscPDFLib((Bitmap)mlist.get(j));
                                this.writeDataImmediately(data);
                            } else {
                                data = PDFUtils.drawTscPDF((Bitmap)mlist.get(j));
                                this.writeDataImmediately(data);
                            }

                            print = "\r\nPRINT 1\r\n";
                            this.writeDataImmediately(print.getBytes("GB18030"));
                        }

                        if (i == bitmaps.length - 1) {
                            mlist.clear();
                            return true;
                        }
                    }
                }

                return false;
            }
        }
    }

    public boolean writeBitmapToTsc(Bitmap mBitmap, int printWidth, boolean cut, boolean dpi200, boolean compression, int cutHeight) throws Exception {
        if (mBitmap == null) {
            throw new Exception("Bitmap cannot be empty");
        } else if (TextUtils.isEmpty(String.valueOf(printWidth))) {
            throw new Exception("printWidth cannot be empty");
        } else if (TextUtils.isEmpty(String.valueOf(cutHeight))) {
            throw new Exception("cutHeight cannot be empty");
        } else {
            if (mBitmap != null) {
                int width = (printWidth + 7) / 8 * 8;
                int height = mBitmap.getHeight() * width / mBitmap.getWidth();
                Log.d("BMP", "bmp.getWidth() " + mBitmap.getWidth());
                Bitmap rszBitmap = GpUtils.resizeImage(mBitmap, width, height);
                List<Bitmap> mlist = ImageCrop(rszBitmap, cutHeight);

                for(int j = 0; j < mlist.size(); ++j) {
                    String size = "\r\nSIZE " + ((Bitmap)mlist.get(j)).getWidth() / (dpi200 ? 8 : 12) + " mm," + ((Bitmap)mlist.get(j)).getHeight() / (dpi200 ? 8 : 12) + " mm\r\n";
                    this.writeDataImmediately(size.getBytes("GB18030"));
                    String gap = "GAP 0 mm,0 mm\r\n";
                    this.writeDataImmediately(gap.getBytes("GB18030"));
                    if (cut && j == mlist.size() - 1) {
                        this.writeDataImmediately("SET CUTTER 1\r\n".getBytes("GB18030"));
                    } else {
                        this.writeDataImmediately("SET CUTTER OFF\r\n".getBytes("GB18030"));
                    }

                    String cls = "CLS\r\n";
                    this.writeDataImmediately(cls.getBytes("GB18030"));
                    byte[] data = PDFUtils.drawTscPDFLib((Bitmap)mlist.get(j));
                    this.writeDataImmediately(data);
                    String print = "\r\nPRINT 1\r\n";
                    this.writeDataImmediately(print.getBytes("GB18030"));
                    if (j == mlist.size() - 1) {
                        return true;
                    }
                }
            }

            return false;
        }
    }

    public static List<Bitmap> ImageCrop(Bitmap bitmap, int photoheight) {
        List<Bitmap> list = new ArrayList();
        int last = bitmap.getHeight() % photoheight;

        for(int i = 0; i < bitmap.getHeight() - bitmap.getHeight() % photoheight; i += photoheight) {
            list.add(cutBitmap(bitmap, i, photoheight));
        }

        if (last > 0) {
            Bitmap cp = cutBitmap(bitmap, bitmap.getHeight() - bitmap.getHeight() % photoheight, bitmap.getHeight() % photoheight);
            list.add(cp);
        }

        return list;
    }

    public int readData(byte[] bytes) throws IOException {
        this.len = -1;
        if (this.mSocket != null && this.inputStream != null) {
            try {
                if (this.inputStream.available() > 0) {
                    this.len = this.inputStream.read(bytes);
                    LogUtils.e(TAG, "printer data return : \t" + SDKUtils.bytesToHexString(bytes));
                }

                return this.len;
            } catch (IOException var3) {
                Log.e(TAG, "BlueDevice connection device is lost");
                this.isConn = false;
                throw var3;
            }
        } else {
            throw new IOException();
        }
    }

    public synchronized boolean closePort() {
        try {
            this.mPrinterDevices = null;
            this.isConn = false;
            this.command = null;
            if (this.mAdapter != null) {
                this.mAdapter = null;
            }

            if (this.reader != null) {
                this.reader.cancel();
                this.reader.interrupt();
                this.reader = null;
            }

            if (this.mSocket != null) {
                this.mSocket.close();
            }

            if (this.device != null) {
                this.device = null;
            }

            if (this.inputStream != null) {
                this.inputStream.close();
            }

            if (this.outputStream != null) {
                this.outputStream.close();
            }

            if (this.byteArrayOutputStream != null) {
                this.byteArrayOutputStream.close();
            }

            this.macAddress = null;
            LogUtils.e(TAG, "close success");
            return true;
        } catch (IOException var2) {
            LogUtils.e(TAG, "close error" + var2);
            return false;
        }
    }

    class IoReader extends Thread {
        private boolean isRun = true;

        public IoReader() {
        }

        public void cancel() {
            this.isRun = false;
        }

        public void run() {
            while(true) {
                try {
                    if (this.isRun) {
                        LogUtils.e(BluetoothPort.TAG, "读数据...");
                        BluetoothPort.this.len = BluetoothPort.this.inputStream.read(BluetoothPort.this.buffer);
                        LogUtils.e(BluetoothPort.TAG, "len..." + BluetoothPort.this.len);
                        if (BluetoothPort.this.len <= 0) {
                            continue;
                        }

                        synchronized(BluetoothPort.this.lock) {
                            final byte[] receive = SDKUtils.subBytes(BluetoothPort.this.buffer, 0, BluetoothPort.this.len);
                            BluetoothPort.this.byteArrayOutputStream.write(receive);
                            BluetoothPort.this.lock.notifyAll();
                            Thread.sleep(10L);
                            UIThreadManager.onUIThread(new Runnable() {
                                public void run() {
                                    BluetoothPort.this.callbackListener.onReceive(receive);
                                }
                            });
                            continue;
                        }
                    }
                } catch (Exception var5) {
                    BluetoothPort.this.isConn = false;
                    if (BluetoothPort.this.callbackListener != null) {
                        UIThreadManager.onUIThread(new Runnable() {
                            public void run() {
                                LogUtils.e(BluetoothPort.TAG, "断开连接");
                                BluetoothPort.this.callbackListener.onDisconnect();
                            }
                        });
                    }
                }

                return;
            }
        }
    }
}

